package com.zkingsoft.externalInterface.weixinUtil;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.math.BigDecimal;
import java.net.URLEncoder;
import java.util.Map;
import java.util.SortedMap;
import java.util.TreeMap;

import javax.servlet.http.HttpServletRequest;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import com.matrix.core.exception.GlobleException;
import com.matrix.core.tools.LogUtil;
import com.matrix.core.tools.StringUtils;
import com.matrix.core.tools.WebUtil;
import com.zkingsoft.externalInterface.business.JsApiPayBusiness;
import com.zkingsoft.externalInterface.common.WechatConfigure;
import com.zkingsoft.externalInterface.protocol.paramProtocol.BrandWCPayRequestData;
import com.zkingsoft.externalInterface.protocol.payComProtocol.JsApiPayComReqData;
import com.zkingsoft.externalInterface.protocol.payComProtocol.JsApiPayComResData;
import com.zkingsoft.externalInterface.protocol.payProtocol.JsApiPayReqData;
import com.zkingsoft.externalInterface.protocol.payProtocol.JsApiPayResData;
import com.zkingsoft.externalInterface.protocol.queryProtocol.ScanPayQueryReqData;
import com.zkingsoft.externalInterface.protocol.queryProtocol.ScanPayQueryResData;
import com.zkingsoft.externalInterface.protocol.refundProtocol.RefundReqData;
import com.zkingsoft.externalInterface.protocol.refundProtocol.RefundResData;
import com.zkingsoft.externalInterface.service.JsApiPayComService;
import com.zkingsoft.externalInterface.service.RefundService;
import com.zkingsoft.externalInterface.service.ScanPayQueryService;

/**微信工具类
 * @author guchunxia
 *
 */
@Service(value="weixinServiceUtil")
public class WeixinServiceUtil {
	static Logger logger=Logger.getLogger(WeixinServiceUtil.class);

	/**
	 * 是否为debug模式
	 */
	@Value("${debug}")
	private String debug;
	
	/**
	 * 支付"175.9.82.254"
	 * WebUtil.getRequest().getRemoteAddr()
	 * getRemortIP(WebUtil.getRequest())
	 * @Description 公众号支付，生成预支付订单
	   @date 2017年6月27日
	   @atuhor guchunxia
	 * @param desc 描述信息
	 * @param outTradeNo 订单id
	 * @param price 订单价格，类型为整型，单位是分，不是元，等于你的实际价格*100
	 * @param openId  支付者的微信openId
	 * @return 预支付订单返回的结果对象（该结果对象已封装），在H5页面使用该对象信息
	 * @throws Exception
	 */
	public BrandWCPayRequestData createOrder(String desc,String outTradeNo, int price, String openId,String attach) throws Exception {
		// 创建微信支付预付接口
		JsApiPayBusiness jsApiPayBusiness = new JsApiPayBusiness();
		JsApiPayReqData jsApiPayReqData = new JsApiPayReqData(desc, outTradeNo, price,getIpAddr(WebUtil.getRequest())
				, openId,attach);
		// 创建预付订单并返回请求结果
		JsApiPayResData result = jsApiPayBusiness.createPrapareOrder(jsApiPayReqData);
		// 把预付订单的信息存放在request域中
		WebUtil.getRequest().setAttribute("msg", result.toString());
		LogUtil.info("#---返回码：return_code = {}" , result.getReturn_code());
		LogUtil.info("#---签名信息：return_msg = {}" , result.getReturn_msg());
		if (result.getReturn_code().equals("SUCCESS")) {
			// 请求成功， 构建BrandWCPayRequest发起支付需要的参数
			BrandWCPayRequestData payData = new BrandWCPayRequestData(result.getPrepay_id());
			WebUtil.getRequest().setAttribute("payData", payData);
			return payData;
		}
			return null;
	}
	
	
	/**@Description 支付后，向微信发送请求、查询订单，看订单是否真的支付成功了
	   @date 2017年6月27日
	   @atuhor guchunxia
	 * @param transactionID 微信生成的订单id transactionID和trUuid任意一个即可，另外一个可为空，若两个参数都不为空则transactionID优先
	 * @param trUuid 系统(项目中)产生的原订单id
	 * @param orderPrice 原订单的价格
	 * @return
	 */
	public boolean isPaySuccess(String transactionID,String trUuid){
		    boolean isSucess=false;
			try {
				JsApiPayBusiness jsApiPayBusiness = new JsApiPayBusiness();
				ScanPayQueryReqData scanPayQueryReqData = new ScanPayQueryReqData(transactionID, trUuid);
				ScanPayQueryService scanPayQueryService = new ScanPayQueryService();
				ScanPayQueryResData result = jsApiPayBusiness.queryPrapareOrder(scanPayQueryService, scanPayQueryReqData);
				WebUtil.getRequest().setAttribute("msg", result.toString());
				//订单金额相等
				//isSucess=result.getTotal_fee().equals(orderPrice.multiply(new BigDecimal("100")).doubleValue()+"");
				
				if (result.getReturn_code().equals("SUCCESS")) {
					isSucess=true;
				}
			}  catch (Exception e) {
				LogUtil.error("#查询订单异常#transactionID:{}#trUuid:{}", e, transactionID,trUuid);
			}
			return isSucess;
	}
	/**@Description 用户提现提现审核，企业付款到个人
	   @date 2017年5月26日
	   @atuhor guchunxia
	 * @param desc 描述
	 * @param outTradeNo  提现申请编号
	 * @param totalFee 提现金额（分）
	 * @param spBillCreateIP 调用接口的IP
	 * @param openid
	 * @return
	 */
	public JsApiPayComResData comPay(String desc, String outTradeNo,int totalFee, String openid){
		JsApiPayComResData result=null;
		//boolean flag=false;
		try {
			JsApiPayBusiness jsApiPayBusiness = new JsApiPayBusiness();
			JsApiPayComReqData jsApiPayComReqData=new JsApiPayComReqData(desc, outTradeNo, totalFee,openid);
			JsApiPayComService jsApiPayComService=new JsApiPayComService();
			result = jsApiPayBusiness.payComOrder(jsApiPayComService, jsApiPayComReqData);
			LogUtil.info("#提现，企业付款到个人---result:{}",result);
			if (result.getResult_code().equals("SUCCESS")) {
				return result;
			}else{
				 throw new GlobleException(result.getErr_code_des());
			}
		} catch (Exception e) {
			LogUtil.error("#企业付款到个人异常#提现#outTradeNo:{}#opUserID:{}", e, outTradeNo,openid);
		}
		return null;
	}
	
	
	/**@Description 退款，企业付款到个人
	   @date 2017年5月26日
	   @atuhor guchunxia
	 * @param outTradeNo 商户订单编号（原订单编号）
	 * @param outRefundNo 退款编号
	 * @param totalFee 原订单金额（分）
	 * @param refundFee 退款金额（分）
	 * @param opUserID 操作员id,默认为商户号
	 * @return
	 */
	public boolean comRefund(String outTradeNo, String outRefundNo,int totalFee,
			int refundFee, String opUserID){
		LogUtil.info("#---outTradeNo:{}#---outRefundNo:{}#---totalFee:{}#---refundFee:{}",
				outTradeNo,outRefundNo,totalFee,refundFee);
		if(opUserID==null){
			opUserID=WechatConfigure.mchID;
		}
		RefundResData result=null;
		boolean flag=false;
		try {
			JsApiPayBusiness jsApiPayBusiness = new JsApiPayBusiness();
			RefundReqData refundReqData=new RefundReqData(outTradeNo, outRefundNo, totalFee, refundFee,opUserID);
			RefundService refundService=new RefundService();
			result = jsApiPayBusiness.refundComOrder(refundService, refundReqData);
			LogUtil.info("#退款，企业付款到个人---result:{}",result);
		} catch (Exception e) {
			LogUtil.error("#企业付款到个人异常#退款#outTradeNo:{}#opUserID:{}", e, outTradeNo,opUserID);
		}
		
		if (result.getResult_code().equals(WechatConfigure.SUCCESS)) {
			 flag=true;
		}else{
			 flag=false;
			 throw new GlobleException(result.getErr_code_des());
		}
		return flag;
	}
	
	/**@Description 支付获取远程设备的ip
	   @date 2017年6月27日
	   @atuhor guchunxia
	 * @param request
	 * @return
	 */
	public String getIpAddr(HttpServletRequest request) { 
	       String ip = request.getHeader("x-forwarded-for"); 
	      /* if(ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) { 
	           ip = request.getHeader("Proxy-Client-IP"); 
	       } 
	       if(ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) { 
	           ip = request.getHeader("WL-Proxy-Client-IP"); 
	       } */
	       if(ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) { 
	           ip = request.getRemoteAddr(); 
	       } 
	       if(ip!=null){
	        ip=ip.split(",")[0];
	       }
	       return ip; 
	   } 
	
	
}
